﻿using AiMoWindows.Localization;
using AiMoWindows.MainActions;
using AiMoWindows.MainActions.SecondaryActions;
using System.Windows;
using System.Windows.Input;

namespace AiMoWindows.Windows.Login
{
    class LoginWindowViewModel : ChangeLanguageViewModelBase
    {
        readonly LoginWindow owner;
        public LoginWindowViewModel(LoginWindow loginWindow) : base()
        {
            owner = loginWindow;
            LoginCommand = new RelayCommand(Login_Button_Click);
            NewUserCommand = new RelayCommand(ActionsUtils.OpenTutorialWeb);
        }
        public ICommand LoginCommand { get; }
        public ICommand NewUserCommand { get; }
        public string TitleText => IsEnglish ? "AiMo User Login" : "AiMo 用户登录";
        public string UserNameText => IsEnglish ? "User Name" : "用户名";
        public string PasswordText => IsEnglish ? "Password" : "密码";
        public string NewUserButtonText => IsEnglish ? "New User" : "新用户";
        public string LoginButtonText => IsEnglish ? "Log in" : "登录";

        string m_Username = "";
        public string UserName
        {
            get => m_Username;
            set
            {
                m_Username = value;
                RaisePropertyChanged(nameof(UserName));
            }
        }
        public void Login_Button_Click()
        {
            if (IsValidUserName())
            {
                LoginController controller = new LoginController(UserName, owner.Password, ShowMessage);
                controller.OnLoginSuccess += Controller_OnLoginFinish;
                new Thread(new ThreadStart(controller.Login)).Start();
            }
        }
        void Controller_OnLoginFinish(object? sender, EventArgs e)
        {
            owner.Dispatcher.InvokeAsync(() =>
            {
                owner.DialogResult = true;
                owner.Close();
            });
        }
        void ShowMessage(string message, string title)
        {
            owner.Dispatcher.InvokeAsync(() =>
            {
                MessageBox.Show(owner, message, title);
            });
        }
        bool IsValidUserName()
        {
            if (UserName.Length < 3)
            {
                MessageBox.Show(owner, Local.Get("Username should be at least 3 characters"));
                return false;
            }
            if (owner.Password.Length < 6)
            {
                MessageBox.Show(owner, Local.Get("Password should be at least 6 characters"));
                return false;
            }
            return true;
        }
    }
}
